package com.myapp.db.dao.base;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

import com.myapp.data.define.BaseBean;
import com.myapp.data.global.Instances;
import com.myapp.db.config.define.BaseDao;
import com.myapp.db.config.define.UpdateData;
import com.myapp.db.entity.UserEntity;

/**
 * 文件名：BaseUserDao.java
 * <p>
 * 功能：活动表是直接操作数据库的Dao,由系统自动生成,不建议修改
 * <p>
 * 作者：Builded by AppTools.
 */
public class BaseUserDao extends BaseDao {
	// 日志
	private Logger log = Logger.getLogger(BaseUserDao.class);

	@Override
	public <T extends BaseBean> int insert(T entity) throws Exception {
		String sql = "insert into User values(?,?,?,?,?)";
		Connection conn = null;
		PreparedStatement ppstat = null;
		int back = 0;
		try {
			conn = Instances.getConnectionFactory().getDBConnection();
			ppstat = conn.prepareStatement(sql);
			// ID
			ppstat.setLong(1, entity.getId());
			// 用户id
			ppstat.setLong(2, ((UserEntity) entity).getUserid());
			// passportid
			ppstat.setString(3, ((UserEntity) entity).getPassportid());
			// 是否可用（0:正常，1:各种异常）
			ppstat.setInt(4, ((UserEntity) entity).getIsactive());
			// 此条记录最后修改时间
			ppstat.setLong(5, ((UserEntity) entity).getUpdatetime());
			back = ppstat.executeUpdate();
		} catch (Exception e) {
			log.error("Insert failures", e);
		} finally {
			if (ppstat != null) {
				try {
					ppstat.close();
				} catch (SQLException e) {
				}
				ppstat = null;
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
				}
				conn = null;
			}
		}
		return back;
	}

	@Override
	public <T extends BaseBean> int update(T entity) throws Exception {
		StringBuffer sb = new StringBuffer();
		sb.append("update User set ");
		
		if (entity.getOldData().isEmpty()) {
			return 0;
		} else {
			Entry<String, UpdateData> entry = null;
			String key;
			UpdateData data;
			Object value;
			// 循环设置要修改的数据
			Iterator<Entry<String, UpdateData>> itr = entity.getOldData()
					.entrySet().iterator();
			while (itr.hasNext()) {
				entry = itr.next();
				key = entry.getKey();
				data = entry.getValue();
				value = data.getNewData();
				// 根据类型设置数据
				if (value instanceof Integer || value instanceof Long) {
					sb.append(" " + key + " = " + value + ",");
				} else if (value instanceof String) {
					sb.append(" " + key + " = '" + value + "',");
				}
			}

			sb.deleteCharAt(sb.length() - 1);

			// 设置id
			sb.append(" where id= "+entity.getId());
			
			// 更新数据库
			int count = 0;
			Connection conn = null;
			Statement stat = null;
			try {
				conn = Instances.getConnectionFactory().getDBConnection();
				stat = conn.createStatement();
				count = stat.executeUpdate(sb.toString());
			} catch (Exception e) {
				log.error("Update failures", e);
			} finally {
				if (stat != null) {
					try {
						stat.close();
					} catch (SQLException e) {
					}
					stat = null;
				}
				if (conn != null) {
					try {
						conn.close();
					} catch (SQLException e) {
					}
					conn = null;
				}
			}
			return count;
		}
	}

	@Override
	public <T extends BaseBean> int delete(T entity) throws Exception {
		String sql = "delete from User where id= ?";
		// 更新数据库
		int count = 0;
		Connection conn = null;
		PreparedStatement ppstat = null;
		try {
			conn = Instances.getConnectionFactory().getDBConnection();
			ppstat = conn.prepareStatement(sql);
			ppstat.setLong(1, entity.getId());
			count = ppstat.executeUpdate();
		} catch (Exception e) {
			log.error("Delete failures", e);
		} finally {
			if (ppstat != null) {
				try {
					ppstat.close();
				} catch (SQLException e) {
				}
				ppstat = null;
			}
			
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
				}
				conn = null;
			}
		}
		return count;
	}

	@Override
	public <T extends BaseBean> T get(long id, Class<T> clazz) throws Exception {
		String sql = "select * from User where id=?";
		Connection conn = null;
		PreparedStatement ppstat = null;
		ResultSet rest = null;
		T entity = null;
		try {
			conn = Instances.getConnectionFactory().getDBConnection();
			ppstat = conn.prepareStatement(sql);
			ppstat.setLong(1, id);
			rest = ppstat.executeQuery();
			if (rest.next()) {
				entity = clazz.newInstance();
				entity.parseEntity(rest);
			}
		} catch (Exception e) {
			log.error("Get Entity failures", e);
		} finally {
			if (rest != null) {
				try {
					rest.close();
				} catch (SQLException e) {
				}
				rest = null;
			}

			if (ppstat != null) {
				try {
					ppstat.close();
				} catch (SQLException e) {
				}
				ppstat = null;
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
				}
				conn = null;
			}
		}
		return entity;
	}

	@Override
	public <T extends BaseBean> List<T> findAllByUid(long uid, Class<T> clazz)
			throws Exception {
		String sql = "select * from  User where uid=?";
		Connection conn = null;
		PreparedStatement ppstat = null;
		ResultSet rest = null;
		List<T> entitys = new ArrayList<T>();
		T entity = null;
		try {
			conn = Instances.getConnectionFactory().getDBConnection();
			ppstat = conn.prepareStatement(sql);
			ppstat.setLong(1, uid);
			rest = ppstat.executeQuery();
			if (rest.next()) {
				entity = clazz.newInstance();
				entity.parseEntity(rest);
				entitys.add(entity);
			}
		} catch (Exception e) {
			log.error("FindAllByUid Failure", e);
		} finally {
			if (rest != null) {
				try {
					rest.close();
				} catch (SQLException e) {
				}
				rest = null;
			}

			if (ppstat != null) {
				try {
					ppstat.close();
				} catch (SQLException e) {
				}
				ppstat = null;
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
				}
				conn = null;
			}
		}
		return entitys;	
	}

	@Override
	public void createTable() {
		StringBuilder sb = new StringBuilder();

		sb.append("CREATE TABLE IF NOT EXISTS User ");

		sb.append("( ");
		// 添加Id
		sb.append("Id bigint(19) NOT NULL DEFAULT 0");
		
		// 添加列用户id
		sb.append(",userid bigint(13)  COMMENT '用户id 用户id'");

		// 添加列passportid
		sb.append(",passportid varchar(50)  COMMENT 'passportid passportid'");

		// 添加列是否可用（0:正常，1:各种异常）
		sb.append(",isactive smallint(1)  COMMENT '是否可用（0:正常，1:各种异常） 是否可用（0:正常，1:各种异常）'");

		// 添加列此条记录最后修改时间
		sb.append(",updatetime bigint(13)  COMMENT '此条记录最后修改时间 此条记录最后修改时间'");

		
		// 添加主键
		sb.append(",PRIMARY KEY(Id,userid) ");

		// 添加索引
		sb.append(" )");
		// 创建表
		Connection conn = null;
		Statement stat = null;
		try {
			conn = Instances.getConnectionFactory().getDBConnection();
			stat = conn.createStatement();
			stat.executeUpdate(sb.toString());
		} catch (Exception e) {
			log.error("Create table failures", e);
			System.exit(1);
		} finally {
			if (stat != null) {
				try {
					stat.close();
				} catch (SQLException e) {
				}
				stat = null;
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
				}
				conn = null;
			}
		}
	}

	@Override
	public void truncateTable() throws Exception {
		String sql = "TRUNCATE TABLE User";
		Connection conn = null;
		Statement stat = null;
		try {
			conn = Instances.getConnectionFactory().getDBConnection();
			stat = conn.createStatement();
			stat.executeUpdate(sql);
		} catch (Exception e) {
			log.error("Truncate table failures", e);
		} finally {
			if (stat != null) {
				try {
					stat.close();
				} catch (SQLException e) {
				}
				stat = null;
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
				}
				conn = null;
			}
		}	
	}

	@Override
	public int countAll() throws Exception {
		String sql = "select count(1) from  User";
		Connection conn = null;
		Statement stat = null;
		ResultSet rest = null;
		int count = 0;
		try {
			conn = Instances.getConnectionFactory().getDBConnection();
			stat = conn.createStatement();
			rest = stat.executeQuery(sql);
			while (rest.next()) {
				count = rest.getInt(1);
			}
		} catch (Exception e) {
			log.error("Count all failures", e);
		} finally {
			if (rest != null) {
				try {
					rest.close();
				} catch (SQLException e) {
				}
				rest = null;
			}
			if (stat != null) {
				try {
					stat.close();
				} catch (SQLException e) {
				}
				stat = null;
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
				}
				conn = null;
			}
		}
		return count;
	}

	@Override
	public long getMaxId() {
		String sql = "select Max(id) from User";
		Connection conn = null;
		Statement stat = null;
		ResultSet rest = null;
		long maxId = 0;
		try {
			conn = Instances.getConnectionFactory().getDBConnection();
			stat = conn.createStatement();
			rest = stat.executeQuery(sql);
			if (rest.next()) {
				maxId = rest.getLong(1);
			}
		} catch (Exception e) {
			log.error("Get max id Failure", e);
		} finally {
			if (rest != null) {
				try {
					rest.close();
				} catch (SQLException e) {
				}
				rest = null;
			}
			if (stat != null) {
				try {
					stat.close();
				} catch (SQLException e) {
				}
				stat = null;
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
				}
				conn = null;
			}
		}
		return maxId;
	}
}
